package com.lxk.controller;

import com.lxk.pojo.Seckill;
import com.lxk.service.GoodsStatService;
import com.lxk.service.SeckillService;
import com.lxk.util.SeckillOrderTimerTask;
import com.lxk.vo.result.CodeMsg;
import com.lxk.vo.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;

@Controller
@RequestMapping("/deprcated/seckill")
public class SeckillController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private SeckillService ss;
	@Autowired
	private GoodsStatService gss;

	/**
	 * 定时订单检查间隔30秒
	 */
	private final static long orderPeriod = 30*1000;
	
	/**
	 * 时间类型转换
	 * @param binder
	 */
	@InitBinder  
	public void initBinder(WebDataBinder binder) {  
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");  
	    dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
	}

	/**
	 * 设置新一期秒杀
	 * @param req
	 * @param seckill
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/set", method = RequestMethod.POST)
	public Result<Integer> setNewSeckill(HttpServletRequest req, @Validated Seckill seckill) {
		
		//将seckill存入表
		Date seckillBeginTime = seckill.getSeckillBeginTime();
		if(seckillBeginTime.before(new Date())){
			return Result.error(CodeMsg.SECKILL_TIME_ERROR);
		}
		Integer seckillId = ss.setSeckill(seckill);

		//将商品设为拍卖商品，并从普通商品中下架
		Integer set = gss.setGoodsSeckill(seckill.getGoodsId(), 1);
		if(set==0) {
			return Result.error(CodeMsg.MYSQL_CRUD_FAIL);
		}

		//设置定时检查过期订单任务
		Timer orderTimer = new Timer();
		orderTimer.scheduleAtFixedRate(new SeckillOrderTimerTask(orderTimer, seckillId), seckillBeginTime, orderPeriod);

		return Result.success(1);
	}
	
}
